<template>
  <div>
    <h1 v-if="hasPermission">用户管理页面</h1>
    <h1 v-else>权限不足</h1>
    <el-card v-if="hasPermission" class="box-card">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="请输入用户名"
          clearable
          class="search-input"
        />
        <el-button type="primary" @click="fetchUsers">搜索</el-button>
        <el-button type="success" @click="openCreateDialog">新增用户</el-button>
      </div>

      <!-- 数据表格 -->
      <el-table :data="users" border style="width: 100%" v-loading="loading">
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="rolename" label="角色" />
        <el-table-column prop="teamname" label="团队" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="电话" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 新增用户弹窗 -->
    <el-dialog v-model="createDialogVisible" title="新增用户">
      <el-form :model="createForm" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="createForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="createForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="createForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="createForm.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="角色">
                 <el-select
    v-model="createForm.roleId"
    placeholder="选择角色"
    @change="updateRoleName"
  >
    <el-option
      v-for="role in roles"
      :key="role.id"
      :label="role.rolename"
      :value="role.id"
    ></el-option>
  </el-select>
        </el-form-item>
               <el-form-item label="团队">
          <el-select
            v-model="createForm.teamId"
            placeholder="选择团队"
            @change="updateTeamName"
          >
            <el-option
              v-for="team in teams"
              :key="team.id"
              :label="team.teamname"
              :value="team.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCreate">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

// 权限检查
const roleId = parseInt(localStorage.getItem('roleId'), 10); // 从 localStorage 获取 roleId
const hasPermission = roleId === 1 || roleId === 2 || roleId === 3;
// 角色列表状态
const roles = ref([]);

// 获取角色列表
const fetchRoles = async () => {
  try {
    const token = localStorage.getItem('token'); // 从 localStorage 获取 token
    if (!token) {
      throw new Error('未找到 token，请重新登录');
    }

    const response = await axios.get('http://localhost:8080/role/page', {
      params: {
        current: 1,
        size: 10,
      },
      headers: {
        Authorization: `Bearer ${token}`, // 添加 Authorization 头
      },
    });

    roles.value = response.data.data.records; // 将角色数据存储到 roles 状态中
  } catch (error) {
    console.error('获取角色数据失败:', error);
    ElMessage.error('获取角色数据失败，请稍后重试');
  }
};

// 页面加载时获取角色数据
fetchRoles();
// 状态
const users = ref([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
const loading = ref(false);
const searchQuery = ref('');

// 新增用户弹窗状态
const createDialogVisible = ref(false);
const createForm = reactive({
  username: '',
  password: '',
  email: '',
  phone: '',
  roleId: null,
  rolename: '', // 存储角色名
  teamId: null,
  teamname: '', // 存储团队名
});
// 团队列表状态
const teams = ref([]);

// 获取团队列表
const fetchTeams = async () => {
  try {
    const token = localStorage.getItem('token'); // 从 localStorage 获取 token
    if (!token) {
      throw new Error('未找到 token，请重新登录');
    }

    const response = await axios.get('http://localhost:8080/team/page', {
      params: {
        current: 1,
        size: 10,
      },
      headers: {
        Authorization: `Bearer ${token}`, // 添加 Authorization 头
      },
    });

    teams.value = response.data.data.records; // 将团队数据存储到 teams 状态中
  } catch (error) {
    console.error('获取团队数据失败:', error);
    ElMessage.error('获取团队数据失败，请稍后重试');
  }
};

// 页面加载时获取团队数据
fetchTeams();
// 获取用户列表
const fetchUsers = async () => {
  if (!hasPermission) return; // 如果没有权限，直接返回
  loading.value = true;
  try {
    const token = localStorage.getItem('token'); // 从 localStorage 获取 token
    if (!token) {
      throw new Error('未找到 token，请重新登录');
    }

    const response = await axios.get('http://localhost:8080/user/page', {
      params: {
        current: currentPage.value,
        size: pageSize.value,
        username: searchQuery.value || undefined,
      },
      headers: {
        Authorization: `Bearer ${token}`, // 添加 Authorization 头
      },
    });

    const { records, total: totalRecords } = response.data.data;
    users.value = records;
    total.value = totalRecords;
  } catch (error) {
    console.error('获取用户数据失败:', error);
    ElMessage.error('获取用户数据失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 删除用户
const handleDelete = async (user) => {
  try {
    const token = localStorage.getItem('token'); // 从 localStorage 获取 token
    if (!token) {
      throw new Error('未找到 token，请重新登录');
    }

    await ElMessageBox.confirm(
      `确定要删除用户 "${user.username}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    await axios.delete(`http://localhost:8080/user/${user.id}`, {
      headers: {
        Authorization: `Bearer ${token}`, // 添加 Authorization 头
      },
    });

    ElMessage.success('用户删除成功');
    fetchUsers(); // 刷新用户列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error);
      ElMessage.error('删除用户失败，请稍后重试');
    }
  }
};

// 打开新增用户弹窗
const openCreateDialog = () => {
  createDialogVisible.value = true;
};

// 提交新增用户
const submitCreate = async () => {
  try {
    const token = localStorage.getItem('token'); // 从 localStorage 获取 token
    if (!token) {
      throw new Error('未找到 token，请重新登录');
    }

    await axios.post(
      'http://localhost:8080/user/create',
      createForm,
      {
        headers: {
          Authorization: `Bearer ${token}`, // 添加 Authorization 头
          'Content-Type': 'application/json',
        },
      }
    );

    ElMessage.success('用户创建成功');
    createDialogVisible.value = false;
    fetchUsers(); // 刷新用户列表
  } catch (error) {
    console.error('创建用户失败:', error);
    ElMessage.error('创建用户失败，请稍后重试');
  }
};

// 分页切换
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchUsers();
};

// 页面加载时获取数据
fetchUsers();
</script>

<style scoped>
.box-card {
  margin: 20px;
  padding: 20px;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>